﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace NamedPipeWrapper.IO
{
    public class PipeStreamWrapperEx<TRead, TWrite>
        where TRead : class
        where TWrite : class
    {
        /// <summary>
        /// Gets the underlying <c>PipeStream</c> object.
        /// </summary>
        public PipeStream BaseStream { get; private set; }

        public bool IsConnected
        {
            get { return BaseStream.IsConnected && _reader.IsConnected; }
        }

        public bool CanRead
        {
            get { return BaseStream.CanRead; }
        }

        public bool CanWrite
        {
            get { return BaseStream.CanWrite; }
        }

        private readonly PipeStreamReaderEx<TRead> _reader;
        private readonly PipeStreamWriterEx<TWrite> _writer;

        public PipeStreamWrapperEx(PipeStream stream)
        {
            BaseStream = stream;
            _reader = new PipeStreamReaderEx<TRead>(BaseStream);
            _writer = new PipeStreamWriterEx<TWrite>(BaseStream);
        }

        public TRead ReadObject()
        {
            return _reader.ReadObject();
        }

        public async Task<TRead> ReadObjectAsync()
        {
            return await _reader.ReadObjectAsync();
        }

        public void WriteObject(TWrite obj)
        {
            _writer.WriteObject(obj);
        }

        public async Task WriteObjectAsync(TWrite obj)
        {
            await _writer.WriteObjectAsync(obj);
        }

        public void Close()
        {
            BaseStream.Close();
        }
    }
}
